<script setup>
import { onMounted, ref } from 'vue';
import { ElTable, ElTableColumn, ElButton } from "element-plus";
import * as echarts from 'echarts';
import axios from "axios";
import {delUser, getUsers} from "@/api/getData.js";


// <ComponentSmartClock ref="demo9_4" type="countdown" format="hh:mm:ss" :timelong="20000" @end="end9_4" linecolor="#fd5151" :linewidth="5" style="width:300px;height:40px;padding-bottom:10px" styletype="style6"></ComponentSmartClock>


const userData = ref([]);
const loading = ref(false);

const columns = ref([
  { prop: 'userId', label:'用户名' ,width: 200 },
  { prop: 'username', label: '用户名', width: 200 },
  { prop: 'password', label: '密码', width: 200 },
  { prop: 'role', label: '角色', width: 200 },
  { prop: 'classId', label: '班级ID', width: 200 },
  { prop: 'createdAt', label: '创建时间', width: 200 },
]);
onMounted(() => {
  getEltableColumns();
});



const getEltableColumns = () => {
  getUsers()
      .then(res => {
        console.log(res.datas);
        userData.value = res.datas;

// 动态生成列定义
        console.log(userData.value);
        const firstDataItem = userData.value.length > 0 ? userData.value[0] : {};
        console.log(firstDataItem);
        const keys = Object.keys(firstDataItem);
        console.log(keys);
        columns.value = keys.map(key => ({
          prop: key,
          label: key.charAt(0).toUpperCase() + key.slice(1),
          width: 150,
          sortable: true // 可以根据需要添加排序功能
        }));

        console.log('Data loaded and assigned:', userData.value); // 确保在数据准备好后调用

        updatePieChart();
        updateBarChart();

      })
      .catch(error => {
        console.error('Error fetching data:', error);
      })
      .finally(() => {
        loading.value = false;
      });
};

const updatePieChart = () => {
  if (!userData.value || userData.value.length === 0) {
    console.log('No data available to update the chart');
    return;
  }

// 计算学生、老师、家长人数
  let studentCount = userData.value.filter(user => user.role === '学生').length;
  let teacherCount = userData.value.filter(user => user.role === '老师').length;
  let parentCount = userData.value.filter(user => user.role === '家长').length;

  let myChart = echarts.init(document.getElementById('myChartDiagnosis'));
  let option = {
    color: ['#37A2DA', '#32C5E9', '#9FE6B8'],
    title: {
      text: '用户角色分布',
      x: 'center'
    },
    tooltip: {
      trigger: 'item',
      confine: true
    },
    legend: {
      orient: 'vertical',
      right: '10%',
      top: 'middle',
      icon: 'circle',
      itemWidth: 10,
      itemHeight: 10,
      textStyle: {
        color: 'grey',
        fontSize: 12
      },
      data: ['学生', '老师', '家长']
    },
    series: [
      {
        type: 'pie',
        radius: '60%',
        center: ['40%', '50%'],
        label: {
          show: true,
          fontSize: 12,
          formatter: '{b} {d}%'
        },
        data: [
          {value: studentCount, name: '学生'},
          {value: teacherCount, name: '老师'},
          {value: parentCount, name: '家长'}
        ]
      }
    ]
  };
  myChart.setOption(option);
};

const updateBarChart = () => {
  const myChart = echarts.init(document.getElementById('myChartBar')); // 确保你的 DOM 中有一个这个 ID 的元素
  const option = {
    xAxis: {
      type: 'category',
      data: ['学生', '老师', '家长'],
      axisLabel: {
        textStyle: {
          color: '#333' // x轴标签颜色
        }
      },
      axisLine: {
        lineStyle: {
          color: '#ccc' // x轴线颜色
        }
      }
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        textStyle: {
          color: '#333' // y轴标签颜色
        }
      },
      axisLine: {
        lineStyle: {
          color: '#ccc' // y轴线颜色
        }
      },
      splitLine: {
        lineStyle: {
          color: '#eee', // y轴分隔线颜色
          type: 'dashed' // y轴分隔线类型
        }
      }
    },
    tooltip: {
      trigger: 'item',
      confine: true,
      backgroundColor: 'rgba(50, 150, 250, 0.8)', // 提示框背景色
      textStyle: {
        color: '#fff' // 提示框文字颜色
      }
    },
    series: [
      {
        data: [
          userData.value.filter(user => user.role === '学生').length,
          userData.value.filter(user => user.role === '老师').length,
          userData.value.filter(user => user.role === '家长').length
        ],
        type: 'bar',
        itemStyle: {
          color: 'skyblue' // 柱状图颜色
        }
      }
    ],
    legend: {
      data: ['学生', '老师', '家长'],
      textStyle: {
        color: '#666' // legend 文字颜色
      },
      itemWidth: 14, // 图例标记的图形宽度
      itemHeight: 10, // 图例标记的图形高度
      itemGap: 20, // 图例每项之间的间隔
      backgroundColor: '#f5f5f5', // legend 背景色
      borderRadius: 5, // legend 边框圆角
      padding: [10, 15] // legend 内边距
    }
  };

  myChart.setOption(option);
}


const delById = (row )=>{

    console.log('sfasfa',row.userId);
  delUser(row.userId)
      .then(res => {
        if (res && res.data) {
          console.log('Delete successful:', res.data);
// 进行其他操作，例如更新界面等
        } else {
          console.error('Error: Response or data is undefined.');
        }
      })
      .catch(error => {
        console.error('Error deleting user:', error);
      });
};

</script>


<template>
   <div class="container">
    <!-- 标题行 -->
    <div class="title-row">
     <h2>用户数据表和图表展示</h2>
    </div>
    <div class="table-echart">
     <!-- 左侧表格 -->
     <div class="table-container" >
      <el-table class="el-table"
         :data="userData"
         height="500"
         v-loading="loading"
         :row-key="row => row.userId"
        >
       <el-table-column class="el-table__row"
          v-for="column in columns"
          :key="column.prop"
          :prop="column.prop"
          :label="column.label"
          :width="column.width"
          sortable
         >
       </el-table-column>
       <el-table-column label="操作" width="150" class="el-table__row">
         <template v-slot="{row}">
        <el-button type="danger" size="mini" @click="delById(row)">删除</el-button>
         </template>
       </el-table-column>
      </el-table>

     </div>
     <!-- 右侧图表区域 -->
     <div class="chart-container">
      <div class="chart-title">柱状图示例</div>
      <div id="myChartDiagnosis" class="chart" style="width: 100%; height: 300px;"></div>
      <div id="myChartBar" class="chart" style="width: 100%; height: 300px;">12342344123</div>
     </div>
    </div>
   </div>
</template>

<style scoped>
.container {
  min-height: 100vh;
  min-width:100vw;
   width: 100%;
   overflow: hidden;
   background-color: #f0f9ff; /* 使用偏向天蓝色的背景 */
   display: flex;
   flex-direction: column;
   align-items: center; /* 居中内容 */
   padding: 20px; /* 添加整体内边距 */
   border-radius: 8px; /* 圆角边框 */
   box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1); /* 添加轻微的阴影 */
}

.title-row {
   margin-bottom: 20px;
   text-align: center;
   background-color: #7ec8e3; /* 偏向天蓝色的背景色 */
   padding: 10px;
   color: #fff;
   border-radius: 5px;
   box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.table-echart {
   width: 100%;
   display: flex;
   justify-content: space-between;
}

.table-container {
   width: 53%; /* 调整宽度，留出空间给图表区域 */
   background-color: #cfe7f5;
   border-radius: 8px;
   box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
   overflow: hidden;
  flex-direction: column;
  display: flex;
}

.table-container .el-table {
   font-size: 14px;
   color: #333;
  flex: 1;
  min-height: 100%;
}

.table-container .el-table .el-table__row {
   border-bottom: 1px solid #ddd;
}

.table-container .el-table .el-table__row:hover {
   background-color: #f0f9ff;
}

.chart-container {
   width: 45%; /* 调整宽度，与表格容器并排 */
   background-color: #cfe7f5;
   border-radius: 8px;
   box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
   overflow: hidden;
   display: flex;
   flex-direction: column;
   align-items: center; /* 图表内容居中 */
}

.chart-title {
   background-color: #7ec8e3; /* 图表标题的背景色 */
   color: #fff;
   padding: 8px 16px;
   border-top-left-radius: 8px;
   border-top-right-radius: 8px;
   text-align: center;
   width: 100%;
}

.chart {
   width: 100%;
   height: 300px;
   margin-bottom: 20px;
}
.duiming{
  font-size: 12px;

}
</style>
